package com.zfl.thread.day04;

import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class ReentrantReadWriteLockDemo05 {

    private static class MyCache {
        private final HashMap<String, String> map = new HashMap<>();
        private final ReentrantReadWriteLock reentrantReadWriteLock = new ReentrantReadWriteLock();

        public void put(String key, String val) {
            reentrantReadWriteLock.writeLock().lock();
            try {
                Thread.sleep(500);
                map.put(key, val);
                System.out.println(Thread.currentThread().getName() + "写入数据");
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            } finally {
                reentrantReadWriteLock.writeLock().unlock();
            }
        }

        public void get(String key) {
            reentrantReadWriteLock.readLock().lock();
            try {
                Thread.sleep(500);
                String val = map.get(key);
                System.out.println(Thread.currentThread().getName() + ":" + val);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            } finally {
                reentrantReadWriteLock.readLock().unlock();
            }
        }

    }


    public static void main(String[] args) throws InterruptedException {
        MyCache myCache = new MyCache();
        CountDownLatch countDownLatch = new CountDownLatch(5);
        for (int i = 0; i < 5; i++) {
            int finalI = i;
            new Thread(() -> {
                myCache.put(finalI + "", UUID.randomUUID().toString().substring(0, 4));
                countDownLatch.countDown();
            }, "写线程-" + i + "-").start();
        }
        countDownLatch.await();
        for (int i = 0; i < 5; i++) {
            int finalI = i;
            new Thread(() -> {
                myCache.get(finalI + "");
            }, "读线程-" + i + "-").start();
        }
    }
}
